<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="景点名称" prop="attractionName">
        <el-input
          v-model="queryParams.attractionName"
          placeholder="请输入景点名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="省份名称" prop="provinceName">
        <el-select
              v-model="queryParams.provinceName"
              placeholder="请选择省份名称"
              @change="handleQueryProvinceChange" style="width: 190px;"
            >
              <el-option
                v-for="province in provinces"
                :key="province.cityCode"
                :label="province.cityName"
                :value="province.cityName"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="城市名称" prop="cityName">
        <el-select
              v-model="queryParams.cityName"
              placeholder="请选择城市名称" style="width: 190px;"
            >
              <el-option
                v-for="city in citys"
                :key="city.cityCode"
                :label="city.cityName"
                :value="city.cityName"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="区县名称" prop="areaName">
        <el-input
          v-model="queryParams.areaName"
          placeholder="请输入区县名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地区拼音" prop="regionPinyin">
        <el-input
          v-model="queryParams.regionPinyin"
          placeholder="请输入地区拼音"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="景点等级" prop="attractionLevel">
        <el-select
            v-model="queryParams.attractionLevel"
            placeholder="请选择景点等级" style="width: 190px;">
            <el-option label="A" value="1"></el-option>
            <el-option label="AA" value="2"></el-option>
            <el-option label="AAA" value="3"></el-option>
            <el-option label="AAAA" value="4"></el-option>
            <el-option label="AAAAA" value="5"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入详细地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="景点经度" prop="attractionLongitude" v-show="false">
        <el-input
          v-model="queryParams.attractionLongitude"
          placeholder="请输入景点经度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="景点纬度" prop="attractionLatitude" v-show="false">
        <el-input
          v-model="queryParams.attractionLatitude"
          placeholder="请输入景点纬度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门票价格" prop="ticketPrice">
        <el-input
          v-model="queryParams.ticketPrice"
          placeholder="请输入门票价格"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开放时间" prop="openingHours">
        <el-input
          v-model="queryParams.openingHours"
          placeholder="请输入开放时间"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="推荐指数" prop="recommendScore">
       <el-rate 
              v-model="queryParams.recommendScore" 
              :max="5"
              :allow-half="false" 
              class="custom-rate"  style="width: 190px;"
            />
      </el-form-item>
      <el-form-item label="所属城市是否热门" prop="isHotCity">
        <el-select
            v-model="queryParams.isHotCity"
            placeholder="请选择城市是否热门" style="width: 190px;">
            <el-option label="热门" value="1"></el-option>
            <el-option label="非热门" value="0"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="景点是否热门" prop="isHotAttraction">
        <el-select
            v-model="queryParams.isHotAttraction"
            placeholder="请选择景点是否热门" style="width: 190px;">
            <el-option label="热门" value="1"></el-option>
            <el-option label="非热门" value="0"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="是否有效" prop="isActive">
        <el-select
            v-model="queryParams.isActive"
            placeholder="请选择是否有效" style="width: 190px;">
            <el-option label="有效" value="1"></el-option>
            <el-option label="无效" value="0"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin-top: 30px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['travel:attraction:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['travel:attraction:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['travel:attraction:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['travel:attraction:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attractionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="景点名称" align="center" prop="attractionName" />
      <el-table-column label="省份名称" align="center" prop="provinceName" />
      <el-table-column label="城市名称" align="center" prop="cityName" />
      <el-table-column label="区县名称" align="center" prop="areaName" />
      <el-table-column label="景点等级" align="center" prop="attractionLevel">
        <template #default="scope">
          <span>{{ scope.row.attractionLevel}}A级</span>
        </template>
      </el-table-column>
      <el-table-column label="景点描述" align="center" prop="description" width="125">
        <template #default="scope">
          <el-tooltip effect="dark" :content="scope.row.description" placement="top">
            <div class="text-ellipsis" style="width: 200px;">{{ scope.row.description }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="景点经度" align="center" prop="attractionLongitude" v-if="false" />
      <el-table-column label="景点纬度" align="center" prop="attractionLatitude" v-if="false" />
      <el-table-column label="门票价格" align="center" prop="ticketPrice" />
      <el-table-column label="开放时间" align="center" prop="openingHours" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="主图URL" align="center" prop="image" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="推荐指数" align="center" prop="recommendScore" width="120">
        <template #default="scope">
          <el-rate 
            v-model="scope.row.recommendScore" 
            :max="5" 
            :allow-half="false" 
            :disabled="true"
            class="custom-rate" 
          />
        </template>
      </el-table-column>
      <el-table-column label="所属城市是否热门" align="center" prop="isHotCity">
        <template #default="scope">
          {{ scope.row.isHotCity===1?'热门':'非热门' }}
        </template>
      </el-table-column>
      <el-table-column label="景点是否热门" align="center" prop="isHotAttraction">
        <template #default="scope">
          {{ scope.row.isHotAttraction===1?'热门':'非热门' }}
        </template>
      </el-table-column>
      <el-table-column label="是否有效" align="center" prop="isActive">
        <template #default="scope">
          {{ scope.row.isActive===1?'有效':'无效' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['travel:attraction:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['travel:attraction:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改旅游景点（含地区信息）对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="attractionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="景点名称" prop="attractionName">
          <el-input v-model="form.attractionName" placeholder="请输入景点名称" />
        </el-form-item>
        <el-form-item label="省份名称" prop="provinceName">
           <el-select
              v-model="form.provinceName"
              placeholder="请选择省份名称"
              @change="handleProvinceChange"
            >
              <el-option
                v-for="province in provinces"
                :key="province.cityCode"
                :label="province.cityName"
                :value="province.cityName"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="城市名称" prop="cityName">
           <el-select
              v-model="form.cityName"
              placeholder="请选择城市名称" @change="handleCityChange">
              <el-option
                v-for="city in citys"
                :key="city.cityCode"
                :label="city.cityName"
                :value="city.cityName"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="区县名称" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入区县名称" />
        </el-form-item>
        <el-form-item label="景点等级" prop="attractionLevel">
          <el-select
            v-model="form.attractionLevel"
            placeholder="请选择景点等级" style="width: 190px;">
            <el-option label="A" value="1"></el-option>
            <el-option label="AA" value="2"></el-option>
            <el-option label="AAA" value="3"></el-option>
            <el-option label="AAAA" value="4"></el-option>
            <el-option label="AAAAA" value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="景点描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="景点经度" prop="attractionLongitude" v-show="false">
          <el-input v-model="form.attractionLongitude" placeholder="请输入景点经度" />
        </el-form-item>
        <el-form-item label="景点纬度" prop="attractionLatitude" v-show="false">
          <el-input v-model="form.attractionLatitude" placeholder="请输入景点纬度" />
        </el-form-item>
        <el-form-item label="门票价格" prop="ticketPrice">
          <el-input v-model="form.ticketPrice" placeholder="免费请输入0" />
        </el-form-item>
        <el-form-item label="开放时间" prop="openingHours">
          <el-radio-group v-model="form.timeType" @change="handleTimeTypeChange">
            <el-radio label="allDay">全天开放</el-radio>
            <el-radio label="custom">自定义时间</el-radio>
          </el-radio-group>
          <div v-if="form.timeType === 'custom'" class="time-picker-group">
            <el-time-picker
              v-model="form.startTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="开始时间"
              style="width: 120px; margin-right: 10px"
            />
            <span>至</span>
            <el-time-picker
              v-model="form.endTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="结束时间"
              style="width: 120px; margin-left: 10px"
            />
          </div>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="主图URL" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="推荐指数" prop="recommendScore">
          <el-rate 
              v-model="form.recommendScore" 
              :max="5"
              :allow-half="false" 
              class="custom-rate" 
            />
        </el-form-item>
        <el-form-item label="是否有效" prop="isActive">
          <el-select
            v-model="form.isActive"
            placeholder="请选择是否有效" style="width: 190px;">
            <el-option label="有效" value="1"></el-option>
            <el-option label="无效" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请选择标签大类" prop="tagCategory">
          <el-select
              v-model="form.tagCategory"
              placeholder="请选择标签大类"
              clearable
              style="width: 100%" @change="handleTagCategoryChange">
              <el-option
                v-for="item in tagCategoryOptions"
                :key="item.value"
                :label="item.label"  
                :value="item.value"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="请选择景点标签" prop="tagName">
          <el-select
              v-model="selectedTagids" multiple
              placeholder="请选择景点标签"
              clearable
              style="width: 100%">
              <el-option
                v-for="item in tagNameOptions"
                :key="item.value"
                :label="item.label"  
                :value="item.value"
              />
            </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Attraction">
import { listAttraction, getAttraction, delAttraction, addAttraction, updateAttraction,getProvincesData,getCitys } from "@/api/travel/attraction"
import { getTagCategoryList,getTagNameList } from "@/api/travel/tag"
import { ElTimePicker } from 'element-plus';
const { proxy } = getCurrentInstance()

const attractionList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const provinces = ref([])
const citys = ref([])
const tagCategoryOptions = ref([])
const tagNameOptions = ref([])
const selectedTagids = ref([])

const data = reactive({
  form: {
    openingHours: "",
    timeType: "allDay",
    startTime: "",
    endTime: ""
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    attractionName: null,
    provinceId: null,
    provinceName: null,
    cityId: null,
    cityName: null,
    areaName: null,
    regionPinyin: null,
    attractionLevel: null,
    description: null,
    address: null,
    attractionLongitude: null,
    attractionLatitude: null,
    ticketPrice: null,
    openingHours: null,
    contactPhone: null,
    image: null,
    recommendScore: null,
    isHotCity: null,
    isHotAttraction: null,
    isActive: null,
  },
  rules: {
    attractionName: [
      { required: true, message: "景点名称不能为空", trigger: "blur" }
    ],
    provinceName: [
      { required: true, message: "省份名称不能为空", trigger: "blur" }
    ],
    cityName: [
      { required: true, message: "城市名称不能为空", trigger: "blur" }
    ],
    ticketPrice: [
      { required: true, message: "门票价格不能为空", trigger: "blur" },
      { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入有效的金额（最多两位小数）", trigger: "blur" }
    ],
    recommendScore: [
      { required: true, message: "推荐指数不能为空", trigger: "change" },
      { 
        validator(rule, value, callback) {
          if (typeof value !== "number") {
            callback(new Error("推荐指数必须是数字"));
          } else if (value < 1 || value > 5) {
            callback(new Error("推荐指数必须在 1 到 5 之间"));
          } else {
            callback();
          }
        },
        trigger: "change"
      },
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询旅游景点（含地区信息）列表 */
function getList() {
  loading.value = true
  listAttraction(queryParams.value).then(response => {
    attractionList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    attractionId: null,
    attractionName: null,
    provinceId: null,
    provinceName: null,
    cityId: null,
    cityName: null,
    areaName: null,
    regionPinyin: null,
    attractionLevel: null,
    description: null,
    address: null,
    attractionLongitude: null,
    attractionLatitude: null,
    ticketPrice: null,
    openingHours: null,
    contactPhone: null,
    image: null,
    recommendScore: null,
    isHotCity: null,
    isHotAttraction: null,
    isActive: null,
    createTime: null,
    updateTime: null
  }
  selectedTagids.value=[];
  proxy.resetForm("attractionRef")
}

onMounted(() => {
  form.value.recommendScore = 1; 
  fetchTagCategory()
});

function fetchTagCategory() {
  getTagCategoryList().then(response => {
    tagCategoryOptions.value = response.data.map(item => ({
      label: item.desc, // 显示文本
      value: item.code  // 实际存储值（枚举code）
    }));
  }).catch(error => {
    console.error("获取标签大类枚举失败：", error)
  })
}

function handleTagCategoryChange(tagCategory) {
  const query = {
    tagCategory: tagCategory
  };
  getTagNameList(query).then(res => {
    if (res.code === 200) {
      tagNameOptions.value = res.rows.map(item => ({
        value: item.tagId,
        label: item.tagName
      }));
    }
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.recommendScore = null;
  queryParams.value.provinceId = null;
  queryParams.value.cityId = null;
  queryParams.value.provinceName = null;
  queryParams.value.cityName = null;
  queryParams.value.recommendScore = null;
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.attractionId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加旅游景点（含地区信息）"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _attractionId = row.attractionId || ids.value
  getAttraction(_attractionId).then(response => {
    // 定义 resData 并赋值为后端返回的数据
    let resData = response.data;
    // 关键：将后端返回的字符串转为数字
    resData.recommendScore = Number(resData.recommendScore) || 1;
    // 限制在 1-5 之间
    resData.recommendScore = Math.min(5, Math.max(1, resData.recommendScore));
    selectedTagids.value = resData.selectedTagids || [];
    form.value = { ...resData };
    title.value = "修改旅游景点（含地区信息）";
    open.value = true;
  });
}

function handleTimeTypeChange() {
  if (this.form.timeType === "allDay") {
    this.form.startTime = "";
    this.form.endTime = "";
  }
}

/** 提交按钮 */
function submitForm() {
  if (form.value.recommendScore < 1 || form.value.recommendScore > 5) {
    console.error("推荐指数超出范围：", form.value.recommendScore);
    return;
  }
  proxy.$refs["attractionRef"].validate(valid => {
    if (valid) {
      form.value.tagIds = selectedTagids.value;
      if (form.value.timeType === "allDay") {
        form.value.openingHours = "全天开放";
      } else {
        form.value.openingHours = `${form.value.startTime} - ${form.value.endTime}`;
      }
      if (form.value.attractionId != null) {
        updateAttraction(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addAttraction(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _attractionIds = row.attractionId || ids.value
  proxy.$modal.confirm('是否确认删除旅游景点（含地区信息）编号为"' + _attractionIds + '"的数据项？').then(function() {
    return delAttraction(_attractionIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('travel/attraction/export', {
    ...queryParams.value
  }, `attraction_${new Date().getTime()}.xlsx`)
}

/** 查询表单的省份选择变更处理 */
function handleQueryProvinceChange(provinceName) {
  const selectedProvince = provinces.value.find(province => province.cityName === provinceName);
  queryParams.value.provinceId = selectedProvince ? selectedProvince.cityCode : null;
  queryParams.value.cityName = "";
  if (selectedProvince) {
    getCitiesList(selectedProvince.cityCode);
  } else {
    citys.value = [];
  }
}

// 省份选择变化时的处理函数
function handleProvinceChange(provinceName) {
  const selectedProvince = provinces.value.find(province => province.cityName === provinceName);
  if (selectedProvince) {
    form.value.provinceId = selectedProvince.cityCode;
    getCitiesList(selectedProvince.cityCode);
  } else {
    form.value.provinceId = "";
    citys.value = [];
  }
}

// 城市选择变化时的处理函数
function handleCityChange(cityName) {
  const selectedCity = citys.value.find(city => city.cityName === cityName);
  if (selectedCity) {
    form.value.cityId = selectedCity.cityCode;
  } else {
    form.value.cityId = "";
    citys.value = [];
  }
}

// 获取省份列表
function fetchProvinces() {
  getProvincesData().then(response => {
    // 假设接口返回的省份列表数据在 response.data 中，且每个省份对象有 cityCode（省份ID）和 cityName（省份名称）属性
    provinces.value = response.data;
  }).catch(error => {
    console.error("获取省份列表失败：", error);
  });
}
// 根据省份 ID 获取城市列表
const getCitiesList = (provinceId) => {
  getCitys(provinceId).then(response => {
    citys.value = response.data; 
  }).catch(error => {
    console.error('获取城市列表失败：', error);
  });
};
fetchProvinces();
getList()
</script>
<style scoped>
.custom-rate /deep/ .el-rate__icon {
  font-size: 16px;
}
.text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}
</style>